package com.sync.data.job.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.sync.data.ievent.entity.IeventBasePosition;
import com.sync.data.ievent.repository.IeventBasePositionRepository;
import com.sync.data.mce.entity.MceBasePosition;
import com.sync.data.mce.repository.MceBasePositionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.data.RepositoryItemReader;
import org.springframework.batch.item.database.JpaItemWriter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.PlatformTransactionManager;

import java.util.Collections;
import java.util.Date;

@Configuration
@EnableBatchProcessing
@RequiredArgsConstructor
@Order(2)
public class PositionSyncBatchJob {

    private final JobBuilderFactory jobBuilderFactory;

    private final StepBuilderFactory stepBuilderFactory;

    private final MceBasePositionRepository mceBasePositionRepository;

    private final IeventBasePositionRepository ieventBasePositionRepository;

    private final PlatformTransactionManager transactionManagerIevent;

    private final JpaItemWriter<IeventBasePosition> ieventBasePositionJpaItemWriter;

    // 批处理大小
    private static final int CHUNK_SIZE = 100;

//    @Bean
//    public Job positionSyncJob() {
//        return jobBuilderFactory.get("positionEmployeeSyncJob")
//                .incrementer(new RunIdIncrementer())
//                .start(syncPositionsStep())
//                .build();
//    }

//    public Step prepareWorkNoSetStep() {
//        return stepBuilderFactory.get("prepareWorkNoSetStep")
//                .tasklet((contribution, chunkContext) -> {
//                    // 只存储关键信息，而不是整个集合
//                    int workNoCount = ieventBasePositionRepository.countDistinctWorkNos();
//
//                    // 存储统计信息而不是完整集合
//                    chunkContext.getStepContext()
//                            .getStepExecution()
//                            .getJobExecution()
//                            .getExecutionContext()
//                            .put("workNoCount", workNoCount);
//
//                    // 返回最小必要信息
//                    return RepeatStatus.FINISHED;
//                })
//                .build();
//    }
    @Bean
    public Step syncPositionsStep() {
        return stepBuilderFactory.get("syncPositionsStep")
                .<MceBasePosition, IeventBasePosition>chunk(CHUNK_SIZE)
                .reader(mceBasePositionItemReader())
                .processor(positionSyncProcessor())
                .writer(ieventBasePositionJpaItemWriter)
                .transactionManager(transactionManagerIevent)
                .build();
    }

    public ItemReader<MceBasePosition> mceBasePositionItemReader() {
        RepositoryItemReader<MceBasePosition> reader = new RepositoryItemReader<>();
        reader.setRepository(mceBasePositionRepository);
        reader.setMethodName("findAll");
        reader.setSort(Collections.singletonMap("id", Sort.Direction.ASC));
        reader.setPageSize(CHUNK_SIZE);
        return reader;
    }

    public ItemProcessor<MceBasePosition, IeventBasePosition> positionSyncProcessor() {
        return mceBasePosition -> {
            IeventBasePosition ieventBasePosition= ieventBasePositionRepository.findById(mceBasePosition.getId()).orElse( null);
            if (ieventBasePosition == null) {
                ieventBasePosition = new IeventBasePosition();
                ieventBasePosition.setCreateTime(new Date());
            }
            BeanUtil.copyProperties(mceBasePosition, ieventBasePosition ,
                    CopyOptions.create().setIgnoreProperties("updateTime","createTime"));
            ieventBasePosition.setDelFlag("0");
            ieventBasePosition.setPositionType("division");
            return ieventBasePosition;
        };
    }


}